<template>
  <van-icon :color="collected ? '#ffa500' : ''" :name="collected ? 'star' : 'star-o'" @click="onCollect" />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article.js'
export default {
  name: 'collectArticle',
  data () {
    return {
    }
  },
  model: {
    prop: 'collected',
    event: 'changeCollected'
  },
  props: {
    collected: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  methods: {
    async onCollect () {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '操作中...',
        forbidClick: true // 是否禁止背景点击
      })
      try {
        if (this.collected) {
          // 已收藏，取消收藏
          await deleteCollect(this.articleId)
        } else {
          // 没有收藏，添加收藏
          await addCollect(this.articleId)
        }

        // 更新视图
        // 自定义事件修改数据并不是立即的
        this.$emit('changeCollected', !this.collected)

        this.$toast.success(!this.collected ? '收藏成功' : '取消收藏')
      } catch (err) {
        this.$toast.fail('操作失败，请重试！')
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
</style>
